﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;

using Museum.DBAccess;
using System.IO;

public partial class ClueDetails : System.Web.UI.Page
{
    //for logging to file
    log4net.ILog logger = log4net.LogManager.GetLogger("File");
    string pageMode = string.Empty;
    int newGameID = 0;
    int gameID = 0;
    int clueID = 0;
    int museumID = 0;
    int clueInserted = 0;
    int numberOfClues = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        logger.Info("Starting page load of ClueDetails.aspx");
        if (!Page.IsPostBack)
        {
            if (Request.QueryString["PageMode"] != null)
            {
                pageMode = Request.QueryString["PageMode"].ToString();
                if (pageMode.Equals("New"))
                {
                    ddlGame.Enabled = false;
                    ddlMuseum.Enabled = false;
                }
                else
                {
                    ddlGame.Enabled = true;
                    ddlMuseum.Enabled = true;
                }
            }

            if (Request.QueryString["MuseumID"] != null)
                museumID = Convert.ToInt32(Request.QueryString["MuseumID"].ToString());

            if (Request.QueryString["NewGameID"] != null)
                newGameID = Convert.ToInt32(Request.QueryString["NewGameID"]);

            if (Request.QueryString["GameID"] != null)
                gameID = Convert.ToInt32(Request.QueryString["GameID"]);

            //bind all museums to ddl
            ddlMuseum.DataSource = DBAccess.GetMuseumByCity("");
            ddlMuseum.DataBind();

            DataRow[] dtRows = null;
            DataTable dtGames = null;
            DataTable dtNewGames = null;

            dtGames = DBAccess.GetAllGames();

            if (museumID > 0)
            {
                ddlMuseum.SelectedValue = museumID.ToString();
            }
            else if (Session["SchoolId"] != null && Session["Role"] != null)
            {
                //bind the school museums only
                ddlMuseum.DataSource = DBAccess.GetMuseumBySchoolId(Convert.ToInt32(Session["SchoolId"]));
                ddlMuseum.DataBind();

                //bind games for selected museum
                dtGames.Clear();
                if (Session["MuseumId"] != null)
                {
                    dtGames = DBAccess.GetGameByMuseum(Convert.ToInt32(Session["MuseumId"]));
                }
                else
                    dtGames = DBAccess.GetGameByMuseum(Convert.ToInt32(ddlMuseum.SelectedValue));
            }
            else if (Session["MuseumId"] != null)
            {
                ddlMuseum.SelectedValue = Session["MuseumId"].ToString();
                ddlMuseum.Enabled = false;
            }

            if (dtGames != null && dtGames.Rows.Count > 0)
            {
                if (Session["MuseumId"] != null)
                {
                    dtRows = dtGames.Select("MuseumId=" + Session["MuseumId"].ToString() + "AND GameId < 99999");
                }
                else if (Session["SchoolId"] != null && Session["Role"] != null)
                    dtRows = dtGames.Select("MuseumId=" + ddlMuseum.SelectedValue + "AND GameId > 99999");
                else
                    dtRows = dtGames.Select("MuseumId=" + ddlMuseum.SelectedValue + "AND GameId < 99999");
            }

            dtNewGames = dtGames.Clone();
            if (dtRows != null && dtRows.Length > 0)
            {
                foreach (DataRow row in dtRows)
                {
                    dtNewGames.ImportRow(row);
                }
            }
            if (dtNewGames != null && dtNewGames.Rows.Count > 0)
            {
                ddlGame.DataSource = dtNewGames;
                ddlGame.DataBind();
            }

            if (dtGames != null && dtGames.Rows.Count > 0)
            {
                dtRows = dtGames.Select("GameId=" + ddlGame.SelectedValue);
            }
            if (dtRows != null && dtRows.Length > 0)
            {
                foreach (DataRow row in dtRows)
                {
                    if (!Convert.IsDBNull(row["TotalClues"]))
                        numberOfClues = Convert.ToInt32(row["TotalClues"]);
                }
            }

            if (newGameID > 0)
                ddlGame.SelectedValue = newGameID.ToString();
            else if (gameID > 0)
                ddlGame.SelectedValue = gameID.ToString();

            //check game type and enable/disable controls
            if (Request.QueryString["GameType"] != null)
            {
                if (Request.QueryString["GameType"].Equals("1"))
                {
                    chkIsHint1Answer.Visible = false;
                    chkIsHint2Answer.Visible = false;
                    chkIsHint3Answer.Visible = false;
                    chkIsHint4Answer.Visible = false;
                    lblFindWordAt.Text = "Question";
                    lblHint1.Text = "Option 1";
                    lblHint2.Text = "Option 2";
                    lblHint3.Text = "Option 3";
                    lblHint4.Text = "Option 4";
                }
            }
            if (Request.QueryString["TotalClues"] != null)
            {
                numberOfClues = Convert.ToInt32(Request.QueryString["TotalClues"]);
                BindClueNumbers(numberOfClues);
            }
            else if (numberOfClues > 0)
                BindClueNumbers(numberOfClues);
            else
                btnSubmit.Text = "Submit";

            BindClueData();
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Hashtable hintDetails = null;
        string hintData = string.Empty;
        int result = 0;
        byte[] audioDirectionData = null;
        string audioDirectionURL = string.Empty;
        try
        {
            hintDetails = new Hashtable();

            if (txtHint1.Text.Trim().Length > 0)
                hintDetails.Add("1", txtHint1.Text.Trim().Replace("'", "").Replace("\"", ""));
            if (txtHint2.Text.Trim().Length > 0)
                hintDetails.Add("2", txtHint2.Text.Trim().Replace("'", "").Replace("\"", ""));
            if (txtHint3.Text.Trim().Length > 0)
                hintDetails.Add("3", txtHint3.Text.Trim().Replace("'", "").Replace("\"", ""));
            if (txtHint4.Text.Trim().Length > 0)
                hintDetails.Add("4", txtHint4.Text.Trim().Replace("'", "").Replace("\"", ""));

            hintData = BuildXmlString("Root", hintDetails);

            if (fileAudioDirection.HasFile)
            {
                audioDirectionData = new byte[fileAudioDirection.FileBytes.Length];
                audioDirectionData = fileAudioDirection.FileBytes;

                //Create a new subfolder under the current active folder
                string newPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory + @"GameAssets/", txtFindArt.Text.Trim());

                // Create the subfolder
                System.IO.Directory.CreateDirectory(newPath);

                // Combine the new file name with the path
                newPath = System.IO.Path.Combine(newPath, fileAudioDirection.FileName);

                FileStream fs1 = new FileStream(newPath, FileMode.Create, FileAccess.Write);
                fs1.Write(audioDirectionData, 0, audioDirectionData.Length);
                fs1.Close();

                audioDirectionURL = ConfigurationManager.AppSettings["ServerURL"] + @"GameAssets/" + txtFindArt.Text.Trim() + "/" + fileAudioDirection.FileName;
            }

            result = DBAccess.InsertOrUpdateClueDetails(clueID, Convert.ToInt32(ddlGame.SelectedValue), "", txtDirections.Text.Trim(),
                Convert.ToInt32(ddlClueNumber.SelectedValue), txtFindArt.Text.Trim(), txtFindWordAt.Text.Trim(), txtAnswer.Text.Trim(), chkIsCritical.Checked, 0, audioDirectionURL, hintData);

            if (clueID > 0)
            {
                if (result.Equals(-1))
                {
                    Alert.ShowMessage("Clue updated successfully.");
                }
            }
            else
            {
                if (result.Equals(-1))
                {
                    ViewState["SelectedIndex"] = ddlClueNumber.SelectedIndex;
                    if (Request.QueryString["TotalClues"] != null)
                    {
                        if (btnSubmit.Text.Equals("Create Game"))
                        {
                            Alert.ShowMessage("Game created successfully.");
                            Response.Redirect("ManageGame.aspx", false);
                        }
                        else
                            Alert.ShowMessage("Clue inserted successfully.");
                    }
                    else
                        Alert.ShowMessage("Clue updated successfully.");
                }
            }
            int clueCount = Convert.ToInt32(ViewState["ClueCount"]);
            ViewState["ClueCount"] = clueCount + 1;
            if (Request.QueryString["TotalClues"] != null && ViewState["ClueCount"] != null)
            {
                int count = Convert.ToInt32(ViewState["ClueCount"]);
                if (count + 1 == Convert.ToInt32(Request.QueryString["TotalClues"]))
                {
                    btnSubmit.Text = "Create Game";
                }

                if (ViewState["SelectedIndex"] != null)
                {
                    if (Convert.ToInt32(ViewState["ClueCount"]) < Convert.ToInt32(Request.QueryString["TotalClues"]))
                    {
                        ddlClueNumber.SelectedIndex = Convert.ToInt32(ViewState["SelectedIndex"]) + 1;
                    }
                }
            }
            ClearControls();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private void BindClueNumbers(int numberOfClues)
    {
        DataTable dtNumberOfClues = new DataTable();
        DataRow dtRow = null;
        dtNumberOfClues.Columns.Add("Id");
        dtNumberOfClues.Columns.Add("Value");
        for (int i = 1; i <= numberOfClues; i++)
        {
            dtRow = dtNumberOfClues.NewRow();
            dtRow["Id"] = i;
            dtRow["Value"] = i.ToString();
            dtNumberOfClues.Rows.Add(dtRow);
        }
        ddlClueNumber.DataTextField = "Value";
        ddlClueNumber.DataValueField = "Id";
        ddlClueNumber.DataSource = dtNumberOfClues;
        ddlClueNumber.DataBind();
    }

    /// <summary>
    /// Binds the control data.
    /// </summary>
    private void BindClueData()
    {
        DataTable dtClue = null;
        int clueNumber = 1;
        try
        {
            if (!string.IsNullOrEmpty(ddlClueNumber.SelectedValue))
                clueNumber = Convert.ToInt32(ddlClueNumber.SelectedValue);

            if (Request.QueryString["NewGameID"] != null && Convert.ToInt32(Request.QueryString["NewGameID"]) > 0)
            {
                newGameID = Convert.ToInt32(Request.QueryString["NewGameID"]);
                dtClue = DBAccess.GetClueByGameId(clueNumber, newGameID);
            }
            else if (Request.QueryString["GameID"] != null && Convert.ToInt32(Request.QueryString["GameID"]) > 0)
            {
                gameID = Convert.ToInt32(Request.QueryString["GameID"]);
                dtClue = DBAccess.GetClueByGameId(clueNumber, gameID);
            }
            else if (!string.IsNullOrEmpty(ddlGame.SelectedValue))
            {
                dtClue = DBAccess.GetClueByGameId(clueNumber, Convert.ToInt32(ddlGame.SelectedValue));
            }

            if (gameID > 0)
                ddlGame.SelectedValue = gameID.ToString();
            else if (newGameID > 0)
                ddlGame.SelectedValue = newGameID.ToString();
            //else
            //    ddlGame.SelectedValue = ViewState["GameId"].ToString();

            if (dtClue != null && dtClue.Rows.Count > 0)
            {
                BindClueNumbers(Convert.ToInt32(dtClue.Rows[0]["TotalClues"]));

                clueID = Convert.ToInt32(dtClue.Rows[0]["ClueID"]);
                ddlGame.SelectedValue = dtClue.Rows[0]["GameId"].ToString();
                //txtClueDetails.Text = dtClue.Rows[0]["ClueDetail"].ToString();
                txtDirections.Text = dtClue.Rows[0]["DirectionDetails"].ToString();
                txtAudioDirectionPath.Text = dtClue.Rows[0]["filePath"].ToString();
                txtAudioDirectionPath.ToolTip = dtClue.Rows[0]["filePath"].ToString();
                txtFindArt.Text = dtClue.Rows[0]["LocateArt"].ToString();
                txtFindWordAt.Text = dtClue.Rows[0]["FindWordAt"].ToString();
                txtAnswer.Text = dtClue.Rows[0]["Answer"].ToString();
                chkIsCritical.Checked = Convert.ToBoolean(dtClue.Rows[0]["IsCritical"]);
                //ddlMuseum.SelectedValue = dtClue.Rows[0]["MuseumId"].ToString();
            }
            else
                ClearControls();

            if (dtClue != null && dtClue.Rows.Count > 0)
            {
                txtHint1.Text = dtClue.Rows[0]["HintDescription"].ToString();
                txtHint2.Text = dtClue.Rows[1]["HintDescription"].ToString();
                txtHint3.Text = dtClue.Rows[2]["HintDescription"].ToString();
                txtHint4.Text = dtClue.Rows[3]["HintDescription"].ToString();
                chkIsHint1Answer.Checked = Convert.ToBoolean(dtClue.Rows[0]["IsAnswer"]);
                chkIsHint2Answer.Checked = Convert.ToBoolean(dtClue.Rows[1]["IsAnswer"]);
                chkIsHint3Answer.Checked = Convert.ToBoolean(dtClue.Rows[2]["IsAnswer"]);
                chkIsHint4Answer.Checked = Convert.ToBoolean(dtClue.Rows[3]["IsAnswer"]);
                ViewState["Hint"] = dtClue;
            }
            else
                ClearControls();
        }
        catch (Exception ex)
        {
            logger.Info("ClueDetails.aspx : BindClueData()", ex);
        }
        finally
        {
        }
    }

    private void ClearControls()
    {
        txtDirections.Text = "";
        txtFindArt.Text = "";
        txtFindWordAt.Text = "";
        txtHint1.Text = "";
        txtHint2.Text = "";
        txtHint3.Text = "";
        txtHint4.Text = "";
        txtAnswer.Text = "";
        chkIsHint1Answer.Checked = false;
        chkIsHint2Answer.Checked = false;
        chkIsHint3Answer.Checked = false;
        chkIsHint4Answer.Checked = false;
    }
    protected void btnReset_Click(object sender, EventArgs e)
    {
        ClearControls();
    }

    private DataView SortHashtable(Hashtable hsTable)
    {
        System.Data.DataTable dtValues = new System.Data.DataTable();
        dtValues.Columns.Add(new System.Data.DataColumn("key"));
        dtValues.Columns.Add(new System.Data.DataColumn("value"));

        foreach (DictionaryEntry entry in hsTable)
        {
            DataRow dtRow = dtValues.NewRow();
            dtRow["key"] = entry.Key;
            dtRow["value"] = entry.Value;
            dtValues.Rows.Add(dtRow);
        }

        DataView dtView = new DataView(dtValues);
        dtView.Sort = "key";

        return dtView;
    }

    public string BuildXmlString(string xmlRootName, Hashtable values)
    {
        StringBuilder xmlString = new StringBuilder();

        DataView dtView = SortHashtable(values);
        DataTable dtHints = new DataTable();

        xmlString.AppendFormat("<{0}>", xmlRootName);

        for (int iRow = 0; iRow < dtView.Count; iRow++)
        {
            string key = dtView[iRow]["key"].ToString();
            string value = dtView[iRow]["value"].ToString();

            xmlString.AppendFormat("<Hint");
            if (ViewState["Hint"] != null)
            {
                dtHints = (DataTable)ViewState["Hint"];
                xmlString.AppendFormat(" HintID=\"{0}\"", dtHints.Rows[iRow]["HintID"].ToString());
            }

            xmlString.AppendFormat(" HintDescription=\"{0}\"", value.ToString());
            if (key.Equals("1"))
                xmlString.AppendFormat(" IsAnswer=\"{0}\"", chkIsHint1Answer.Checked ? "True" : "False");
            else if (key.Equals("2"))
            {
                xmlString.AppendFormat(" IsAnswer=\"{0}\"", chkIsHint2Answer.Checked ? "True" : "False");
                xmlString.ToString().Substring(0, xmlString.Length - 1);
            }
            else if (key.Equals("3"))
            {
                xmlString.AppendFormat(" IsAnswer=\"{0}\"", chkIsHint3Answer.Checked ? "True" : "False");
                xmlString.ToString().Substring(0, xmlString.Length - 1);
            }
            else
            {
                xmlString.AppendFormat(" IsAnswer=\"{0}\"", chkIsHint4Answer.Checked ? "True" : "False");
                xmlString.ToString().Substring(0, xmlString.Length - 1);
            }

            xmlString.AppendFormat(" />");
        }
        xmlString.AppendFormat("</{0}>", xmlRootName);

        return xmlString.ToString();
    }

    protected void ddlClueNumber_SelectedIndexChanged(object sender, EventArgs e)
    {
        int clueNumber = Convert.ToInt32(ddlClueNumber.SelectedValue);
        ViewState["GameId"] = ddlGame.SelectedValue;
        BindClueData();
        ddlClueNumber.SelectedValue = clueNumber.ToString();
    }
    protected void ddlGame_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindClueData();
    }
    protected void ddlMuseum_SelectedIndexChanged(object sender, EventArgs e)
    {
        DataRow[] dtRows = null;
        DataTable dtGames = null;
        DataTable dtNewGames = null;
        try
        {
            dtGames = DBAccess.GetAllGames();
            dtRows = dtGames.Select("MuseumId=" + ddlMuseum.SelectedValue);

            dtNewGames = dtGames.Clone();
            foreach (DataRow row in dtRows)
            {
                dtNewGames.ImportRow(row);
            }
            if (dtNewGames != null && dtNewGames.Rows.Count > 0)
            {
                ddlGame.DataSource = dtNewGames;
                ddlGame.DataBind();
            }
            BindClueData();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}
